package com.caipin.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @Author: zhunian0322@163.com
 * @DateTime: 2020-02-21 11:45
 * @Description: TODO
 */
@Component
@Slf4j
public class NettyServer {

    /**
     * boss 线程组用于处理连接工作
     */
    private EventLoopGroup bookGroup = new NioEventLoopGroup();

    /**
     * work 线程组用于数据处理
     */
    private EventLoopGroup workGroup = new NioEventLoopGroup();

    @Value("${netty.dataPort}")
    private int dataPort;

    @PostConstruct
    public void start() throws InterruptedException {
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        serverBootstrap.group(bookGroup, workGroup)
                // 指定Channel
                .channel(NioServerSocketChannel.class)
                //服务端可连接队列数,对应TCP/IP协议listen函数中backlog参数
                .option(ChannelOption.SO_BACKLOG, 1024)
                //设置TCP长连接,一般如果两个小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                //允许重复使用本地地址和端口
                .option(ChannelOption.SO_REUSEADDR, true)

                .childHandler(new NettyServerHandlerInitializer());


        ChannelFuture channelFuture = serverBootstrap.bind(dataPort);

        channelFuture.addListener(future -> {
            if (future.isSuccess()) {
                log.info("Started success,port:{}", dataPort);
            } else {
                log.info("Started Failed,port:{}", dataPort);
            }
        });


        channelFuture.removeListener(future -> {
            log.info("channel close !");
            channelFuture.channel().close();
        });

    }

    @PreDestroy
    public void destroy() throws InterruptedException {
        bookGroup.shutdownGracefully().sync();
        workGroup.shutdownGracefully().sync();
        log.info("关闭 Netty");
    }
}
